<script setup>
import { computed, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import AddDealer from './components/AddDealer.vue'
import ChangeLevel from './components/ChangeLevel.vue'
import AddRemark from './components/AddRemark.vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { handleLogger } from '@renderer/util/common'
import * as XLSX from 'xlsx'

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  levelOpts.value = res
}
handleGetLevelOpts()
const filterState = reactive({
  name: '',
  level: ''
})

const tableCols = [
  {
    key: 'dealer_level_name',
    label: '经销商等级'
  },
  {
    key: 'parent_dealer_name',
    label: '绑定关系'
  },
  {
    key: 'dealer_name',
    label: '经销商名称'
  },
  {
    key: 'teamMoney',
    label: '团队业绩',
    sort: true
  },
  {
    key: 'selfMoney',
    label: '个人业绩',
    sort: true
  },
  {
    key: 'countMoney',
    label: '累计总业绩',
    sort: true
  },
  {
    key: 'dealer_address',
    label: '经销商地址'
  },
  {
    key: 'dealer_mobile',
    label: '经销商电话'
  },
  {
    key: 'dealer_remark',
    label: '备注'
  }
]
const countMoneyNumber = computed(() => {
  let count = 0
  listState.list.forEach((item) => {
    if (!listState.list.some((i) => i.dealer_id === item.parent_dealer_id)) {
      count += Number(item.countMoney)
    }
  })
  return count
})
const listState = reactive({
  page: 1,
  pageSize: 20000000,
  list: [],
  total: 0,
  loading: false
})
async function getDealerList() {
  listState.loading = true
  const res = await window.api.getDealerList(
    listState.pageSize,
    listState.page - 1,
    filterState.level,
    filterState.name
  )
  setTimeout(() => {
    listState.loading = false
  }, 500)
  console.log('经销商列表', res)
  let arr = res.rows || []
  const promises = arr.map(async (item) => {
    item.teamMoney = 0
    item.selfMoney = 0
    const teamRes = await window.api.getDealerPerformance(item.dealer_id, '', '')
    item.teamMoney = Number(teamRes.rows.money).toFixed(2) || 0
    const selfRes = await window.api.getDealerPersonPerformance(item.dealer_id, '', '')
    console.log(selfRes)

    item.selfMoney = Number(selfRes.rows.money).toFixed(2) || 0

    item.countMoney = Number(item.selfMoney) + Number(item.teamMoney)
    item.countMoney = Number(item.countMoney).toFixed(2) || 0
    return item
  })
  const dataArr = await Promise.all(promises)

  listState.list = dataArr
  listState.total = res.total
}
getDealerList()
function changePageNo(page) {
  listState.page = page
  getDealerList()
}

function handleRefreshList() {
  listState.page = 1
  getDealerList()
}

const showCreateLevel = ref(false)
const showCreateDealer = ref(false)

const editItemData = ref(null)
const showChangeLevel = ref(false)
function handleShowChangeLevel(e) {
  editItemData.value = e
  showChangeLevel.value = true
}

const showRemark = ref(false)
function handleShowRemark(e) {
  editItemData.value = e
  showRemark.value = true
}

function handleShowEdit(e) {
  editItemData.value = e
  showCreateDealer.value = true
}

// 删除经销商
async function handleDelDealer(e) {
  await ElMessageBox.confirm(
    '删除后经销商个人业绩，及所有上级团队业绩同步删除，直属下级经销商或团队自动划归为上直属团队。',
    '删除提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  await window.api.deleteDealer(e.dealer_id, e.parent_dealer_id, e.parent_dealer_name)
  ElMessage.success('删除成功')
  handleLogger(`删除经销商：${e.dealer_name}`)
  getDealerList()
}

const exportLoading = ref(false)
async function handleExportData() {
  exportLoading.value = true
  // console.log('当前经销商数据', selectItemData.value, selectKey.value)
  let listData = listState.list || []

  // 设置 Excel 表头
  const headers = [
    '经销商等级',
    '绑定关系',
    '经销商名称',
    '团队业绩',
    '个人业绩',
    '累计总业绩',
    '经销商地址',
    '经销商电话',
    '备注'
  ]

  // 将 listData 转换为合适的格式，每项数据对应 '姓名'、'年龄'、'性别'
  const processedData = listData.map((item) => ({
    经销商等级: item.dealer_level_name,
    绑定关系: item.parent_dealer_name,
    经销商名称: item.dealer_name,
    团队业绩: item.teamMoney,
    个人业绩: item.selfMoney,
    累计总业绩: item.countMoney,
    经销商地址: item.dealer_address,
    经销商电话: item.dealer_mobile,
    备注: item.dealer_remark
  }))

  // 使用 XLSX.utils.json_to_sheet 生成 sheet，添加表头
  const ws = XLSX.utils.json_to_sheet(processedData, { header: headers })

  // 创建新的工作簿
  const wb = XLSX.utils.book_new()
  // 将 sheet 添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 导出 Excel 文件
  XLSX.writeFile(wb, `经销商列表${dayjs().format('YYYYMMDD')}.xlsx`)
  exportLoading.value = false
}
</script>

<template>
  <div v-loading="exportLoading" class="dealer-list-page" element-loading-text="导出数据中...">
    <div class="top-filter-wrap">
      <el-input
        v-model="filterState.name"
        placeholder="请输入经销商名称"
        style="width: 200px"
        :prefix-icon="Search"
        clearable
      ></el-input>
      <el-select
        v-model="filterState.level"
        clearable
        placeholder="请选择经销商等级"
        style="width: 200px"
      >
        <el-option
          v-for="item in levelOpts"
          :key="item.dealer_level_id"
          :label="item.dealer_level_name"
          :value="item.dealer_level_id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="handleRefreshList">查询</el-button>
      <!-- <el-button type="primary" @click="showCreateLevel = true">创建等级</el-button> -->
      <el-button type="primary" @click="(showCreateDealer = true), (editItemData = null)"
        >新增经销商</el-button
      >
      <el-button type="primary" @click="handleExportData">导出</el-button>
    </div>
    <div class="count-box">
      <span>累计总业绩：{{ formatPrice(countMoneyNumber) }} 元</span>
      <span>总人数：{{ listState.total }} 人</span>
    </div>
    <div v-loading="listState.loading" class="table-wrap">
      <el-table :data="listState.list" max-height="1000" style="width: 100%" border>
        <el-table-column
          v-for="item in tableCols"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          align="center"
          :width="item.width"
          :sortable="item.sort ? true : false"
        >
          <template v-if="item.key === 'parent_dealer_name'" #default="scope">
            {{ scope.row.parent_dealer_name }}({{ scope.row.parent_dealer_id }})
          </template>
          <template v-else-if="item.key === 'dealer_name'" #default="scope">
            {{ scope.row.dealer_name }}({{ scope.row.dealer_id }})
          </template>
        </el-table-column>
        <el-table-column prop="opt" label="操作" align="center" width="180px">
          <template #default="scope">
            <!-- <el-button type="primary" link @click="handleShowChangeLevel(scope.row)"
              >调整等级</el-button
            >
            <el-button type="primary" link @click="handleShowRemark(scope.row)">备注</el-button> -->
            <el-button type="primary" link @click="handleShowEdit(scope.row)">编辑</el-button>
            <el-button
              v-if="scope.row.parent_dealer_id"
              type="danger"
              link
              @click="handleDelDealer(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <template #empty>
          <div class="table-no-data">
            <img src="@renderer/assets/img/empty-data.png" />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <!-- <mPage
        :page-size="listState.pageSize"
        :page_no="listState.page"
        style="display: flex; justify-content: flex-end; margin-top: 20px"
        :total="listState.total"
        @handle-current-change="changePageNo"
      /> -->
    </div>
  </div>

  <!-- 创建经销商 -->
  <AddDealer
    v-model:show="showCreateDealer"
    :edit-item-data="editItemData"
    @success="getDealerList"
  />

  <!-- 改变等级 -->
  <ChangeLevel
    v-model:show="showChangeLevel"
    :edit-item-data="editItemData"
    @success="getDealerList"
  />

  <!-- 备注 -->
  <AddRemark v-model:show="showRemark" :edit-item-data="editItemData" @success="getDealerList" />
</template>

<style lang="scss" scoped>
.dealer-list-page {
  .count-box {
    margin-top: 20px;
    margin-bottom: 20px;
    span {
      display: inline-block;
      margin-right: 20px;
    }
  }
}
</style>
